package com.netease.homework.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.netease.homework.service.ICommodityService;

/**
 * 
 * @author smart
 * @时间 2019年3月8日
 * @描述 商品相关controller
 */
@Controller
@RequestMapping("/commodity")
public class CommodityCtrl {

	@Autowired
	@Qualifier("CommodityService")
	private ICommodityService commodityService;
	
	@RequestMapping(value = "/getAllComm", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getAllComm(HttpServletRequest request) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			Map<String, Object> result = commodityService.getAllComm();

			returnMap.put("value", result.get("value"));
			returnMap.put("message", result.get("message"));
			returnMap.put("success", true);
		} catch (Exception e) {
			returnMap.put("message", "异常：失败!");
			returnMap.put("success", false);
			e.printStackTrace();
		}

		return returnMap;
	}
	
	@RequestMapping(value = "/getSelledComm", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getSelledComm(HttpServletRequest request) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			Map<String, Object> result = commodityService.getSelledComm();

			returnMap.put("value", result.get("value"));
			returnMap.put("message", result.get("message"));
			returnMap.put("success", true);
		} catch (Exception e) {
			returnMap.put("message", "异常：失败!");
			returnMap.put("success", false);
			e.printStackTrace();
		}

		return returnMap;
	}
	
	@RequestMapping(value = "/getNoSelledComm", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getNoSelledComm(HttpServletRequest request) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			Map<String, Object> result = commodityService.getNoSelledComm();

			returnMap.put("value", result.get("value"));
			returnMap.put("message", result.get("message"));
			returnMap.put("success", true);
		} catch (Exception e) {
			returnMap.put("message", "异常：失败!");
			returnMap.put("success", false);
			e.printStackTrace();
		}

		return returnMap;
	}
	
	@RequestMapping(value = "/getCommById", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getCommById(HttpServletRequest request,Integer id) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			Map<String, Object> result = commodityService.getCommById(id);

			returnMap.put("value", result.get("value"));
			returnMap.put("message", result.get("message"));
			returnMap.put("success", true);
		} catch (Exception e) {
			returnMap.put("message", "异常：失败!");
			returnMap.put("success", false);
			e.printStackTrace();
		}

		return returnMap;
	}
	
	
	 @RequestMapping(value="/addComm",method= RequestMethod.POST)
	    @ResponseBody
	    public Map<String,Object> addComm(HttpServletRequest request, String name, Double price, String picture,String summary, String description){
	        Map<String,Object> returnMap = new HashMap<String,Object>();

	        try {
	            Map<String,Object> result = commodityService.addComm(name,price,picture,summary,description);
	            returnMap.put("value", result.get("value"));
	            returnMap.put("message", result.get("message"));
	            returnMap.put("success", true);
	        } catch (Exception e) {
	            returnMap.put("message", "异常：失败!");
	            returnMap.put("success", false);
	            e.printStackTrace();
	        }

	        return returnMap;
	    }
	
	  @RequestMapping(value="/editComm",method= RequestMethod.POST)
	    @ResponseBody
	    public Map<String,Object> editComm(HttpServletRequest request,Integer id, String name, Double price,String picture, String summary, String description, Boolean isSelled){
	        Map<String,Object> returnMap = new HashMap<String,Object>();

	        try {
	            Map<String,Object> result = commodityService.editComm(id,name,price,picture,summary,description,isSelled);

	            returnMap.put("value", result.get("value"));
	            returnMap.put("message", result.get("message"));
	            returnMap.put("success", true);
	        } catch (Exception e) {
	            returnMap.put("message", "异常：失败!");
	            returnMap.put("success", false);
	            e.printStackTrace();
	        }

	        return returnMap;
	    }

	    @RequestMapping(value="/deleteComm",method= RequestMethod.POST)
	    @ResponseBody
	    public Map<String,Object> deleteComm(HttpServletRequest request,Integer id){
	        Map<String,Object> returnMap = new HashMap<String,Object>();

	        try {
	            Map<String,Object> result = commodityService.deleteComm(id);

	            returnMap.put("value", result.get("value"));
	            returnMap.put("message", result.get("message"));
	            returnMap.put("success", true);
	        } catch (Exception e) {
	            returnMap.put("message", "异常：失败!");
	            returnMap.put("success", false);
	            e.printStackTrace();
	        }

	        return returnMap;
	    }
	    
	    
	    @RequestMapping(value="/addCommPicture",method= RequestMethod.POST)
	    @ResponseBody
	    public Map<String,Object> addPicture(@RequestParam("uploadfile") MultipartFile file,HttpServletRequest request){
	        Map<String,Object> returnMap = new HashMap<String,Object>();
	        /*System.out.println("start-------------");
	        String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/goods-imgs/");//存储路径
	        System.out.println(ServletFileUpload.isMultipartContent(request));
	        System.out.println(savePath);
	        System.out.println(request);
	        try {
	            if (ServletFileUpload.isMultipartContent(request)) {
	                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	                System.out.println(items);
	                for (FileItem item : items) {
	                        System.out.println("helloosjfos");
	                        String fileType = item.getName().substring(item.getName().lastIndexOf(".") + 1).toLowerCase();//文件类型
	                        String fileName = new Date().getTime() + "." + fileType; //保存的文件名
	                        String filePath = savePath + "\\" + fileName; //保存的文件路径
	                        System.out.println(fileType+fileName+filePath+"---------");
	                        System.out.println(savePath);

	                        BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
	                        BufferedOutputStream out = new BufferedOutputStream(
	                                new FileOutputStream(new File(filePath)));// 获得文件输出流
	                        Streams.copy(in, out, true);// 开始把文件写到指定的上传文件夹
	                        in.close();
	                        out.close();
	                }
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }*/

	        /****************************************************************/
	        try {

	             String savePath = request.getSession().getServletContext().getRealPath("/resources/images/");//存储路径
	            File myPath = new File(savePath);
	            if ( !myPath.exists()){//若此目录不存在，则创建之// 这个东西只能一级建立文件夹，两级是无法建立的。。。。。
	                myPath.mkdir();}
	         
	            String fileName = file.getOriginalFilename();

	            BufferedInputStream bufrs = new BufferedInputStream(file.getInputStream());
	            BufferedOutputStream out = new BufferedOutputStream(
	                    new FileOutputStream(new File(savePath,fileName)));// 获得文件输出流
	            byte[] by = new byte[1024];
	            int ch = 0;
	            while ((ch = bufrs.read(by)) != -1) {
	                out.write(by);
	            }
	            out.flush();
	            out.close();
	            bufrs.close();

	            returnMap.put("success", "图片上传成功");
	        }catch (Exception e){
	            e.printStackTrace();
	        }
	        return returnMap;
	    }
}
